import { DeleteOutlined } from '@ant-design/icons';
import {
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  message,
  Popconfirm,
  Row,
  TreeSelect,
} from 'antd';
import { useEffect, useState } from 'react';
import ImageCrop from '@/components/ImageCrop';
import { uploadFile } from '@/services/file';
import {
  addProduct,
  editProduct,
  getProductCategoryList,
  getProductDetail,
} from '@/services/product';
import { sleep } from '@/utils';
import { gutter } from '../const/keys';
import styles from './index.modules.less';

type Props = {
  id?: number;
  onClose: (reflash: boolean) => void;
};

const App = (props: Props) => {
  const { id, onClose = () => {} } = props;
  const [uploading, setUploading] = useState<boolean>(false);
  const [dataUrls, setDataUrls] = useState<
    {
      filePath?: string;
      dataUrl?: string;
      [key: string]: any;
    }[]
  >([]);
  const [treeData, setTreeData] = useState<any[]>([]);
  const [productPicList, setProductPicList] = useState<string[]>([]);
  const [form] = Form.useForm();

  const ok = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    let { supplyPrice, guidancePrice } = values;
    //前端输入的是元，后端要的是分
    supplyPrice = Math.round(parseFloat(supplyPrice) * 100);
    guidancePrice = Math.round(parseFloat(guidancePrice) * 100);
    values.supplyPrice = supplyPrice;
    values.guidancePrice = guidancePrice;
    values.productPicList = productPicList;

    const { success } =
      id !== undefined
        ? await editProduct({ ...values, id })
        : await addProduct({ ...values });

    if (success) {
      onClose(true);
      message.success(id !== undefined ? '保存成功' : '添加成功');
    }
  };
  const getData = async () => {
    const { data } = await getProductCategoryList({});

    const resetTree = (data: any, parentId?: undefined) => {
      return data?.map((item: any) => ({
        title: item.categoryName,
        value: item.id,
        parentId,
        children: resetTree(item.subList || [], item.id),
      }));
    };

    const formattedTree = resetTree(data);
    setTreeData(formattedTree);
    if (id !== undefined) {
      const { data: detailData } = await getProductDetail({ id });

      let { guidancePrice, supplyPrice, productPicList } = detailData;
      if (productPicList) {
        setDataUrls([...productPicList]);
        setProductPicList(productPicList || []);
      }
      //后端返回的是分，前端要显示元,保留两位小数
      guidancePrice = (guidancePrice / 100).toFixed(2);
      supplyPrice = (supplyPrice / 100).toFixed(2);
      form.setFieldsValue({ ...detailData, guidancePrice, supplyPrice });
    }
  };
  useEffect(() => {
    getData();
  }, []);
  return (
    <Modal
      width={800}
      open={true}
      //点击背景关闭
      maskClosable={false}
      okButtonProps={{
        disabled: uploading,
      }}
      title={`${id !== undefined ? '编辑' : '新建'}产品`}
      onOk={ok}
      onCancel={() => {
        onClose(false);
      }}
    >
      <Form form={form}>
        <Row gutter={gutter}>
          <Col span={12}>
            <Form.Item
              label="产品名称"
              name="productName"
              labelCol={{
                span: 6,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input placeholder="请输入产品名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            {/* 型号规格 */}
            <Form.Item
              label="型号规格"
              name="modelSpecification"
              labelCol={{
                span: 6,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input placeholder="请输入型号规格" />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 产品编码 */}
            <Form.Item
              label="品牌"
              name="brand"
              labelCol={{
                span: 9,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input placeholder="请输入品牌" />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 单位 */}
            <Form.Item
              label="单位"
              name="unit"
              labelCol={{
                span: 9,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input placeholder="请输入单位" maxLength={5} />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 售价 */}
            <Form.Item
              label="产品分类"
              name="productCategoryId"
              rules={[
                {
                  required: true,
                },
              ]}
              labelCol={{
                span: 9,
              }}
            >
              <TreeSelect treeData={treeData} placeholder="请选择产品分类" />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 供货价 */}
            <Form.Item
              label="供货价"
              name="supplyPrice"
              labelCol={{
                span: 9,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <InputNumber
                placeholder="请输入供货价"
                style={{ width: '100%' }}
                precision={2}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 市场指导价 */}
            <Form.Item
              label="市场指导价"
              name="guidancePrice"
              labelCol={{
                span: 9,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <InputNumber
                placeholder="请输入市场指导价"
                style={{ width: '100%' }}
                precision={2}
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            {/* 产品简介 */}
            <Form.Item
              label="产品简介"
              name="productIntroduction"
              labelCol={{
                span: 3,
              }}
            >
              <Input.TextArea rows={4} placeholder="请输入产品简介" />
            </Form.Item>
          </Col>
          <Col span={24}>
            {/* 专业测评 */}
            <Form.Item
              label="专业测评"
              name="professionalEvaluation"
              labelCol={{
                span: 3,
              }}
            >
              <Input.TextArea rows={4} placeholder="请输入专业测评" />
            </Form.Item>
          </Col>
          <Col span={24}>
            {/* 参考图片 */}
            <Form.Item
              label="参考图片"
              name="productPicList"
              labelCol={{
                span: 3,
              }}
            >
              <Row gutter={[gutter, gutter]}>
                <Col span={24} hidden={dataUrls.length === 0}>
                  <Row gutter={[gutter, gutter]}>
                    {dataUrls?.map((item, index) => {
                      const key = `${index}${item.filePath || item.dataUrl}${
                        item.id
                      }`;
                      return (
                        <Col key={key}>
                          <div className={styles.imgBox}>
                            <img
                              src={item.dataUrl || item.filePath}
                              alt={item.fileName || item.originalName}
                              width={150}
                            />
                            <div className={styles.deleteIcon}>
                              <Popconfirm
                                title="确定要删除吗？"
                                onConfirm={() => {
                                  const newDataUrls = dataUrls.filter(
                                    (_, i) => i !== index,
                                  );
                                  const newProductPicList =
                                    productPicList.filter(
                                      (_, i) => i !== index,
                                    );
                                  setDataUrls(newDataUrls);
                                  setProductPicList(newProductPicList);
                                }}
                              >
                                <DeleteOutlined />
                              </Popconfirm>
                            </div>
                          </div>
                        </Col>
                      );
                    })}
                  </Row>
                </Col>
                <Col span={24}>
                  <ImageCrop
                    uploading={uploading}
                    onOk={async (dataurl, blob) => {
                      const formData = new FormData();
                      formData.append('name', 'file');
                      formData.append('file', blob as Blob);
                      setUploading(true);
                      const {
                        //  success,
                        data,
                      } = await uploadFile(formData);
                      setDataUrls([...dataUrls, { dataUrl: dataurl }]);
                      setProductPicList([...productPicList, data as string]);
                      await sleep(1000);
                      setUploading(false);
                    }}
                  />
                </Col>
              </Row>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      {/* <Cropper
        image="https://img.huffingtonpost.com/asset/5ab4d4ac2000007d06eb2c56.jpeg?cache=sih0jwle4e&ops=1910_1000"
        crop={crop}
        zoom={zoom}
        // aspect={4 / 3}
        onCropChange={setCrop}
        onCropComplete={onCropComplete}
        onZoomChange={setZoom}
      /> */}
    </Modal>
  );
};
export default App;
